<template>
  <div>
    <div class="pageheader">
      <XHeader
        :left-options="{backText:'', preventGoBack: true}"
        :title="xheader.title"
        class="XHeader"
        @on-click-back="goBack"
      ></XHeader>
    </div>
    <div class="page">
      <div class="block" style="margin-top:15px">
        <div class="addressitembox" @click="onAddressSelect">
          <div style="flex:1" v-if="address">
            <div class="header">
              <span>收货人:{{address.true_name}}</span>
              <span style="color:#666666;font-size:12px">{{address.mob_phone}}</span>
            </div>
            <div class="address" style="color:#666666;">{{address.area_info}}</div>
          </div>
          <div style="flex:1" v-else>选择收货地址</div>
          <div style="margin-left:15px">></div>
        </div>
      </div>

      <div class="blockgrod">
        <div v-for="(item,index) in goodsList" :key="index">
          <div class="item" :class="[!textStock(item.stock).flag ? 'noGoods' : null]">
            <img class="image" :src="item.goods_image_main" mode="aspectFill"/>
            <div class="content">
              <div style="display: flex; justify-content: space-between">
                <div class="title">{{item.goods_name}}</div>
                <div class="price">￥{{(item.internal_price*1).toFixed(2)}}</div>
              </div>
              <div class="num">X{{item.goods_number}}</div>
              <div class="app-specs" v-if="item.sku_name && item.sku_name.length">规格: {{specsName(item.sku_name)}}</div>
              <div class="noGoods-text">
                <span class="noGoods-text-span">{{textStock(item.stock).text}}</span>
                <span class="noGoods-text-span noGoods-text-btn" v-if="!textStock(item.stock).flag"
                      @click="deleteNoStockGoods(item)">删除</span>
              </div>
            </div>
            <!--            <div class="noGoods-text" v-if="item.stock == 0">-->
          </div>
        </div>
      </div>

      <div class="block">
        <div class="listitem">
          <div class="text">用户留言</div>
          <input style="width: 75%" class="input" maxlength="100" v-model="memberRemark" placeholder="100字以内"
                 @focusout="inputBlur" @focusin="inputFocus">
        </div>
      </div>

      <div class="block">
        <div class="listitem" @click="onShowMethod" v-if="!isCQDX && !isCQDXFK">
          <div class="text">支付方式</div>
          <div class="right">{{ payMethodText }}</div>
          <img class="right" src="@/assets/img/right.png">
        </div>

        <div class="listitem quotatPay" @click="onShowQuota" v-if="isPayMethodQuota">
          <div class="text">额度支付</div>
          <div class="right" v-if="quotaList.length">{{textQuotaTip}}</div>
          <div v-else class="right">暂无适用额度</div>
          <img class="right" src="@/assets/img/right.png">
        </div>
      </div>

      <div class="block">
        <div class="listitem">
          <div class="text">优惠券</div>
          <div class="right" v-if="coupon.length<=0">无可用优惠券</div>
          <select v-else
                  v-model="discountCouponListItem"
                  @change="onHandleCoupon"
                  @focusout="inputBlur"
                  :disabled="isNoUseCoupon"
                  @focusin="inputFocus">
            <option value checked>不使用</option>
            <option v-for="(item,index) in coupon" :key="index" :value="item">{{item.coupon_desc}}</option>
          </select>
        </div>
      </div>

      <!--      <div class="block" v-if="isSanXia && ((quotaId <= 0 || !quotaId) || isPayMethodWeiXin)">-->
      <!--暂时西部智谷 重庆饭卡不显示发票栏-->
      <div class="block" v-if="(isPayMethodWeiXin || (isCQDX && quotaList.length)) && !isXBZG && !isCQDXFK">
        <div class="listitem" @click="onInvoice">
          <div class="text">发票</div>
          <!--          <div class="right">{{!invoice?'':invoice.type==0?'个人':invoice.type==1?'单位':'增值税'}}</div>-->
          <div class="right">{{isInvoicePerfect ? '已完善' : '未完善'}}</div>
          <img class="righticon" src="@/assets/img/right.png"/>
        </div>
      </div>

      <div class="blockgrod" style="margin-top:15px">
        <div class="block">
          <div class="listitem">
            <div class="text">商品金额</div>
            <div class="right">￥{{(goods_total*1+0.00000001).toFixed(2)}}</div>
          </div>
        </div>
        <div class="block">
          <div class="listitem">
            <div class="text">运费</div>
            <div class="right">￥{{(freight*1+0.000000001).toFixed(2)}}</div>
          </div>
        </div>
        <!--        <div class="block" v-if="jdFreight!=null">-->
        <!--          <div class="listitem">-->
        <!--            <div class="text">京东运费</div>-->
        <!--            <div class="right">￥{{(jdFreight*1+0.000000001).toFixed(2)}}</div>-->
        <!--          </div>-->
        <!--        </div>-->
        <div class="block" v-if="discountCouponListItem">
          <div class="listitem">
            <div class="text">优惠券</div>
            <div class="right">￥{{(discountCouponListItem.goods_reduce_amount*1+0.00000001).toFixed(2)}}</div>
          </div>
        </div>

        <div class="block" v-if="quotaId && isPayMethodQuota">
          <div class="listitem">
            <div class="text">额度支付</div>
            <div class="right">￥{{finalQuotaAmounts.toFixed(2)}}</div>
          </div>
        </div>

        <div class="block">
          <div class="listitem">
            <div class="text">应付金额</div>
            <div class="right">￥{{(total*1+0.000000001).toFixed(2)}}</div>
          </div>
        </div>
        <div class="block" v-if="isJinDonFreight">
          <div class="listitem" style="font-size: 12px;color: #b0290f">京东商品满99免邮；49及以上99以下运费6元；49以下运费8元</div>
        </div>
      </div>

      <div class="block" style="margin-top: 38px;margin-bottom:15px;position: relative">
        <div class="noGoods-tip" v-if="!isIndent && address.address_id">商品库存不足，请删除无货商品</div>
        <button class="button" @click="onImmediatePayment"
                type="button">提交订单
        </button>
      </div>
    </div>

    <!--额度列表-->
    <div class="shopQuotaSidebar" v-show="isQuota && quotaList.length">

      <div class="shopQuotaSidebar-tit">
        <div class="shopQuotaSidebar-tit-de">额度支付</div>
        <div>请选择一个您要支付的额度</div>
      </div>

      <ul class="shopQuotaSidebar-content">
        <li class="shopQuotaSidebar-content-box" v-for="(item, index) in quotaList" :key="index">

          <div class="app-item-border app-cursor-pointer shopQuotaSidebar-content-list"
               :class="[index === quotaIndex ? 'shopQuotaSidebar-content-list-checked' : '']"
               @click="onHandleQuota(item, index)">
            <img v-if="index === quotaIndex" :src="require('../../../assets/img/icon_quota_min.png')"
                 class="quotaItem-content-list-min">
            <div class="shopQuotaSidebar-content-list-text quotaItem-content-list-name">{{item.quota_name}}</div>
            <div class="shopQuotaSidebar-content-list-text">
              <span class="shopQuotaSidebar-content-list-text-tit">剩余额度 </span>
              <span class="app-text-ellipsis link-active-class shopQuotaSidebar-content-list-text-price">{{item.quota_residue}}</span>
              <span>&nbsp;元</span>
            </div>
            <div class="shopQuotaSidebar-content-list-text">
              <span class="shopQuotaSidebar-content-list-text-tit">适用范围 </span>
              <span class="shopQuotaSidebar-content-list-text-desc">{{item.cate_name}}</span>
            </div>
            <div class="shopQuotaSidebar-content-list-text">
              <span class="shopQuotaSidebar-content-list-text-tit">有效期至 </span>
              <span class="app-text-ellipsis" v-if="parseFloat(item.quota_type)">永久有效</span>
              <span class="app-text-ellipsis" v-else>{{item.end_date}}</span>
            </div>
          </div>
          <!--额度适用商品-->
          <div class="quota-goods" v-if="quotaGoods.length && quotaId === item.id">
            <div class="quota-goods-desc">额度可抵消消费额: <span
              class="app-new-price-bold">￥{{finalQuotaAmount}}</span></div>
            <ul class="quota-goods-con">
              <li class="quota-goods-con-list" v-for="(item, index) in quotaGoods" :key="index">
                <img class="quota-goods-con-list-img"
                     :src="item.goods_image_main">
                <div class="quota-goods-con-list-price">抵扣金额<span
                  class="link-active-class">￥{{item.quota_amount}}</span></div>
              </li>
            </ul>
          </div>
        </li>
      </ul>

      <div class="block" style="margin-top: 32px; margin-bottom: 15px;">
        <button type="button" class="button" @click="onHideQuota">确定</button>
      </div>

    </div>

    <!--设置密码弹框-->
    <modify-quota-pass
      v-model="dialogVisibleQuotaPass"
      v-if="dialogVisibleQuotaPass"
      :isQuotaPass="isQuotaPass"
      :dialogVisibleQuotaPassPay="dialogVisibleQuotaPassPay"
      :setQuotaPass="setQuotaPass"
      :createOrder="createOrder"
      :phone="phone"
    >首次使用请设置额度支付密码
    </modify-quota-pass>

    <!--支付方式-->
    <actionsheet
      v-model="isPayMethod"
      :menus="payMethodList"
      :close-on-clicking-mask="false"
      show-cancel
      @on-click-menu="onMethodList"
    ></actionsheet>

    <!--发票表单-->
    <invoice-form ref="invoiceForm" @invoicePerfect="invoicePerfect" v-model="isInvoiceForm" :isQuota="quotaId"
                  v-show="isInvoiceForm"></invoice-form>
  </div>
</template>

<script>
  import Mall from '../../../dll/mall'
  import Account from '@/dll/account'
  // import Enum from '../../../config/enum'
  import Pay from '@/dll/pay'
  import Util from '@/utils/util'

  import modifyQuotaPass from '../../../components/modifyQuotaPass'
  import invoiceForm from '../../../components/invoiceForm'

  import screen from '@/mixin/screen'

  import specs from '@/mixin/specs'

  export default {
    name: 'mallClearing',
    mixins: [screen, specs],
    components: {
      modifyQuotaPass,
      invoiceForm
    },
    data () {
      return {
        xheader: {
          title: '确认订单'
        },
        isSelectAddressModel: false,
        isSelectInvoiceModel: false,
        goodsList: [],
        goodsStockParams: {
          supplier_goods: [],
          area: {
            area_code: '',
            id: ''
          }
        }, // 获取运费库存参数
        address: {},
        supplier_cart_list: {},
        discountCouponListItem: '',
        total: 0,
        goods_total: 0,
        invoice: null,
        coupon: [],
        freight: 0,
        no_jd_total_freight: 0,
        jdFreight: 0,
        isIndent: true,
        seckillbuy_id: null,
        if_cart: 0,
        wxPayUrl: '',
        isWxPay: false,

        // 额度
        quotaIndex: -1,
        quotaList: [],
        isQuota: false,
        goodsItem: '',
        quotaId: undefined,
        goodsItemNum: [],
        isQuotaPass: undefined,
        quotaGoods: [],
        finalQuotaAmount: 0,
        finalAmount: 0, // 额度抵扣之后的应付金额
        dialogVisibleQuotaPass: false, // 密码框
        dialogVisibleQuotaPassPay: false, // 输密码
        quotaPass: undefined, // 支付密码

        // 订单备注
        memberRemark: '',

        phone: '', // 修改额度密码手机号

        // 支付方式
        isPayMethod: false,
        payMethodList: [
          {
            label: '额度支付',
            value: 0
          },
          {
            label: '微信支付',
            value: 1
          }
        ],
        payMethod: -1,

        // 发票
        isInvoiceForm: false,
        isInvoicePerfect: false,

        // 是否拉了库存
        isInventory: false,

        // 判断是否有京东商品产生运费
        isJinDonFreight: false,

        isNoUseCoupon: false
      }
    },

    watch: {
      address (val, oldVal) {
        if (val && oldVal && (val.address_id !== oldVal.address_id)) {
          if (this.goodsStockParams.supplier_goods && this.goodsStockParams.supplier_goods.length) {
            this.getJdInventory()
          }
          // eslint-disable-next-line no-unused-expressions
          // this.quotaId ? this.onHandleQuota(null, this.quotaIndex) : null
          this.quotaIndex = -1
          this.defaultCheckedAmount()
        }
      },

      'goodsStockParams.supplier_goods' (val, old) {
        if (val.length && val !== old) {
          this.getJdInventory()
        }
      },

      finalQuotaAmounts () {
        this.onTotal()
      },

      quotaId (val) {
        if (parseFloat(val) > 0) {
          this.$refs.invoiceForm.validate = false
        }
      },

      isPayMethodQuota (val, old) {
        if (val && !this.isCQDX && !this.isCQDXFK) {
          if (this.quotaList.length === 1) { // 如果只有一张额度卡 默认选中
            this.onHandleQuota(this.quotaList[0], 0)
          }
          this.isQuota = !!this.quotaList.length
        }
      },

      isInvoiceForm (val, old) {
        if (val) {
          this.onHidden()
        } else {
          this.onAuto()
        }
      }
    },

    mounted () {
      // 如果是重庆电信 默认为额度支付
      if (this.isCQDX || this.isCQDXFK) {
        this.payMethod = 0
      }

      this.onAuto()
    },

    computed: {
      // 是否是微信支付
      isPayMethodWeiXin () {
        return this.payMethod === 1
      },

      // 是否是额度支付
      isPayMethodQuota () {
        return this.payMethod === 0
      },

      // 支付方式文字显示
      payMethodText () {
        if (this.isPayMethodQuota) {
          return '额度支付'
        } else if (this.isPayMethodWeiXin) {
          return '微信支付'
        } else {
          return '请选择支付方式'
        }
      },

      // 额度金额
      finalQuotaAmounts () {
        if (this.isPayMethodQuota) {
          return this.finalQuotaAmount
        } else {
          return 0
        }
      },

      // 单个商品库存文字显示
      textStock () {
        return (stock) => {
          let _stock = parseFloat(stock)
          if (!this.address.address_id || !this.isInventory) {
            return {
              text: '',
              flag: true
            }
          } else {
            if (_stock > 0) {
              return {
                text: '有货',
                flag: true
              }
            } else {
              return {
                text: '无货',
                flag: false
              }
            }
          }
        }
      },

      textQuotaTip () {
        if (this.discountCouponListItem.id) {
          return '额度优惠券不能同时选择'
        }
        if (this.quotaId) {
          return '已选择'
        } else {
          return '选择额度'
        }
      }
    },

    async created () {
      this.items = JSON.parse(this.$route.query.items)
      this.if_cart = this.$route.query.if_cart
      this.seckillbuy_id = this.$route.query.seckillbuy_id || null
      await this.confirmOrder()
      await this.$refs.invoiceForm.getInvoiceList()
    },

    activated () {
      if (this.globalData.tempAddressSelect) {
        this.address = this.globalData.tempAddressSelect
        this.goodsStockParams.area.area_code = this.address.alias
        this.goodsStockParams.area.id = this.address.alias
      }
      if (this.globalData.tempShippingInvoice) {
        this.invoice = this.globalData.tempShippingInvoice
      }
    },

    beforeDestroy () {
      // this.globalData.tempAddressSelect = null
      this.globalData.tempShippingInvoice = null
    },

    methods: {
      onAddressSelect () {
        // this.isSelectAddressModel = true;
        this.$router.push({ name: 'addressSelect' })
      },
      selectAddressEd (address) {
        this.isSelectAddressModel = false
        this.address = address
      },
      onOffAddress () {
        this.isSelectAddressModel = false
      },
      onInvoice () {
        this.isInvoiceForm = true
        // this.$router.push({ name: 'mallInvoice', query: { isQuota: this.quotaId } })
      },
      selectInvoiceEd (invoice) {
        this.isSelectInvoiceModel = false
        this.invoice = invoice
      },
      onOffInvoice () {
        this.isSelectInvoiceModel = false
      },
      checkPay () {
        this.$vux.confirm.show({
          title: '支付',
          content: '是否已支付？',
          cancelText: '未支付',
          confirmText: '已支付',
          // 组件除show外的属性
          onCancel: () => {
            this.$router.replace({
              name: 'mallOrder',
              params: { tabIndex: 1 }
            })
            // 取消
          },
          onConfirm: () => {
            this.$router.replace({
              name: 'mallOrder',
              params: { tabIndex: 1 }
            })
            // 确定
          }
        })
      },
      onBridgeReady (data) {
        // eslint-disable-next-line no-undef
        WeixinJSBridge.invoke('getBrandWCPayRequest', this.wxPayData, res => {
          let msg = '未知错误'
          if (res.err_msg == 'get_brand_wcpay_request:ok') {
            msg = '支付成功'
          }
          if (res.err_msg == 'get_brand_wcpay_request:fail') {
            msg = '支付失败'
          }
          if (res.err_msg == 'get_brand_wcpay_request:cancel') {
            msg = '用户取消支付'
          }
          this.$vux.alert.show({
            title: '提示',
            content: msg,
            onHide: () => {
              this.$router.replace({
                name: 'mallOrder',
                params: { tabIndex: 1 }
              })
            }
          })
        })
      },
      // 创建微信支付订单
      async createWxOrder (sn) {
        let isWeixn = Util.isWeixn()
        let res
        // if (isWeixn) {
        //   res = await Pay.createWxPayOrder(sn, "JSAPI");
        // } else {

        // }
        res = await Pay.createWxPayOrder(sn)
        if (res.code == 0) {
          if (isWeixn) {
            this.wxPayData = res.data
            if (typeof WeixinJSBridge === 'undefined') {
              if (document.addEventListener) {
                document.addEventListener(
                  'WeixinJSBridgeReady',
                  // eslint-disable-next-line no-undef
                  onBridgeReady,
                  false
                )
              } else if (document.attachEvent) {
                document.attachEvent('WeixinJSBridgeReady', this.onBridgeReady)
                document.attachEvent('onWeixinJSBridgeReady', this.onBridgeReady)
              }
            } else {
              this.onBridgeReady()
            }
          } else {
            this.$router.replace({
              name: 'pay',
              params: { id: res.data.pay_sn, wxPayUrl: res.data.mweb_url }
            })
          }
        } else {
          this.$vux.alert.show({
            title: '提示',
            content: res.msg,
            onHide: () => {
              this.$router.replace({
                name: 'mallOrder',
                params: { tabIndex: 1 }
              })
            }
          })
        }
      },

      // 立即支付
      async onImmediatePayment () {
        if (!this.address.address_id) {
          this.$vux.alert.show({
            title: '提示',
            content: '请选择收货地址'
          })
          return
        }

        if (!this.isIndent) {
          this.$vux.alert.show({
            title: '提示',
            content: '商品库存不足 请先删除无货商品',
            buttonText: '查看详情',
            onHide: () => {
              let PageId = document.querySelector('.noGoods')
              window.scrollTo({
                'top': PageId.offsetTop,
                'behavior': 'smooth'
              })
            }
          })
          return
        }

        // 先选择支付方式 （不是重庆电信的情况下才需要选择）
        if (!this.isPayMethodWeiXin && !this.isPayMethodQuota && !this.isCQDX && !this.isCQDXFK) {
          this.$vux.alert.show({
            title: '提示',
            content: '请先选择支付方式'
          })
          return
        }

        // 如果选择了额度支付 但是没有可用额度 给出相应提示 换支付方式（不是重庆电信的情况下才需要选择）
        if (this.isPayMethodQuota && !this.quotaList.length && !this.isCQDX && !this.isCQDXFK) {
          this.$vux.alert.show({
            title: '提示',
            content: '暂无可使用额度卡，请更换支付方式'
          })
          return
        }

        // 如果选择了额度支付 有可用额度 但是用户没有选择额度
        if ((this.isPayMethodQuota) && this.quotaList.length && (this.quotaId === 0 || !this.quotaId)) {
          this.$vux.alert.show({
            title: '提示',
            content: '请选择额度'
          })
          return
        }

        // 判断是否完善了发票信息
        // if ((this.quotaId <= 0 || !this.quotaId || this.isPayMethodWeiXin) && !this.$refs.invoiceForm.validate) {
        // if ((this.quotaId <= 0 || !this.quotaId || this.isPayMethodWeiXin) && !this.isInvoicePerfect) {
        if (!this.isCQDXFK && (this.isPayMethodWeiXin) && !this.isInvoicePerfect) {
          this.$vux.alert.show({
            title: '提示',
            content: '请完善发票信息'
          })
          return
        }

        // 如果是重庆电信饭卡  额度不够的时候 剩下的不能使用微信支付  并且给予相应的文字提示（暂时又更改方案 勿删除）
        if (this.isCQDXFK && (this.total * 1 + 0.000000001).toFixed(2) != 0.00) {
          this.$vux.alert.show({
            title: '提示',
            content: '一卡通余额不足'
          })
          return
        }

        let _this = this
        this.$vux.confirm.show({
          title: '请确认收货信息',
          content: `<div style="text-align: left;margin-bottom: 5px">姓名: ${this.address.true_name}</div>
               <div style="text-align: left;margin-bottom: 5px">电话: ${this.address.mob_phone}</div>
               <div style="text-align: left;margin-bottom: 5px">地址: ${this.address.area_info} ${this.address.address}</div>`,
          async onConfirm () {
            if (_this.quotaId && !_this.quotaPass && (_this.isPayMethodQuota)) { // 是否使用了额度
              if (!_this.phone && !_this.isQuotaPass) {
                _this.$vux.alert.show({
                  title: '提示',
                  content: '当前用户未设置手机号 不能使用额度'
                })
                return
              }

              _this.dialogVisibleQuotaPass = true
              if (_this.isQuotaPass) { // 输密码
                _this.dialogVisibleQuotaPassPay = true
                return
              } else { // 设置密码
                _this.dialogVisibleQuotaPassPay = false
                return
              }
            }
            await _this.createOrder()
          }
        })
      },

      // 创建订单
      async createOrder (e = undefined, quotaPass = undefined) {
        let param = {
          if_cart: this.if_cart,
          buy_item: [],
          address_id: this.address.address_id,
          member_remark: this.memberRemark
        }
        if (this.invoice) {
          param.invoice_id = this.invoice.id
        }
        if (this.discountCouponListItem) {
          param.reduce = this.discountCouponListItem.id
        }
        if (this.seckillbuy_id) {
          param.seckillbuy_id = this.seckillbuy_id
        }
        let items = this.items
        if (param.if_cart == 1) {
          items.map(item => {
            param.buy_item.push(`${item.cart_id}|${item.goods_number}`)
          })
        } else {
          items.map(item => {
            param.buy_item.push(`${item.goods_sku}|${item.goods_number}`)
          })
        }
        param.buy_item = JSON.stringify(param.buy_item)

        // 判断是否完善了发票信息
        if (!this.quotaId || this.isPayMethodWeiXin) {
          param.invoice_info = JSON.stringify(this.$refs.invoiceForm.invoiceInfo)
        }

        if (this.quotaId && (this.isPayMethodQuota)) {
          param.quota_pass = quotaPass || undefined
          param.quota_id = this.quotaId || undefined
          param.quota_amount = this.finalQuotaAmount || undefined
          let quotaItem = []
          if (this.quotaGoods) {
            this.quotaGoods.forEach((item, index) => {
              quotaItem.push(`${item.goods_sku}|${item.quota_amount}`)
            })
          }
          param.quota_item = JSON.stringify(quotaItem) || undefined
        }
        this.$vux.loading.show({
          text: '请稍后'
        })
        let res = await Mall.createOrder(param)
        this.globalData.tempAddressSelect = null
        this.$vux.loading.hide()
        if (res.code == 0) {
          this.$router.replace({
            name: 'payIng',
            params: { sn: res.data.order_sn_arr }
          })
        } else {
          this.$vux.alert.show({
            title: '提示',
            content: res.msg
          })
        }
      },
      // 确认下单
      async confirmOrder () {
        let param = {
          buy_item: [],
          if_cart: this.if_cart
        }
        if (this.seckillbuy_id) {
          param.seckillbuy_id = this.seckillbuy_id
        }
        let items = this.items
        if (param.if_cart == 1) {
          items.map(item => {
            param.buy_item.push(`${item.cart_id}|${item.goods_number}`)
          })
        } else {
          items.map(item => {
            param.buy_item.push(`${item.goods_sku}|${item.goods_number}`)
          })
        }
        param.buy_item = JSON.stringify(param.buy_item)
        this.$vux.loading.show({
          text: '加载中'
        })
        this.address && this.address.alias ? param.area_code = this.address.alias : param.area_code = undefined
        let res = await Mall.confirmOrder(param)
        this.$vux.loading.hide()
        if (res.code == 0) {
          let coupons = res.data.coupon_list.map(item => {
            item.text = item.name
            return item
          })
          this.coupon = coupons
          // this.address = this.globalData.tempAddressSelect ? this.globalData.tempAddressSelect : res.data.delivery_address
          this.goodsList = res.data.goods_list

          // 获取库存需要数据
          let goodsObj = {}
          let goodsItemNum = []
          for (let i = 0; i < this.goodsList.length; i++) {
            goodsItemNum.push(`${this.goodsList[i].goods_sku}|${this.goodsList[i].goods_number}`)
            if (!goodsObj[this.goodsList[i].supplier_id]) {
              goodsObj[this.goodsList[i].supplier_id] = {
                'supplier_id': this.goodsList[i].supplier_id,
                'goods_skus': [{ goods_sku: this.goodsList[i].goods_sku, num: this.goodsList[i].goods_number }]
              }
            } else {
              goodsObj[this.goodsList[i].supplier_id]['goods_skus'].push({
                goods_sku: this.goodsList[i].goods_sku,
                num: this.goodsList[i].goods_number
              })
            }
            if (!this.goodsList[i].stock_state) this.isIndent = false
          }
          this.goodsItemNum = goodsItemNum
          let supplierGoods = []
          for (let x in goodsObj) {
            supplierGoods.push({ supplier_id: x, goods_skus: goodsObj[x]['goods_skus'] })
          }
          this.goodsStockParams.supplier_goods = supplierGoods
          this.address = this.globalData.tempAddressSelect ? this.globalData.tempAddressSelect : res.data.delivery_address
          if (this.address) {
            this.goodsStockParams.area.area_code = this.address.alias
            this.goodsStockParams.area.id = this.address.alias
          }
          this.goods_total = res.data.order_info.amount_goods.replace(',', '')
          this.total = res.data.order_info.amount_order.replace(',', '')

          // this.getJdFreight()
          if (Util.isWeixn()) {
            this.getJsdkConfig()
          }
          await this.getQuotaList()
        } else {
          this.$vux.confirm.show({
            title: '提示',
            content: res.msg,
            showCancelButton: false,
            onConfirm: () => {
              this.$router.back()
            }
          })
        }
      },
      // 获取JD库存
      async getJdInventory () {
        if (!this.goodsStockParams.area.area_code) {
          return
        }
        let params = {
          supplier_goods: JSON.stringify(this.goodsStockParams.supplier_goods),
          area_code: this.goodsStockParams.area.area_code
        }
        this.$vux.loading.show({
          text: '加载中'
        })
        this.isInventory = false
        let res_freight = await Mall.getJdInventory(params)
        this.$vux.loading.hide()
        this.isIndent = true
        var goodsList = this.goodsList
        if (res_freight.code != 0) {
          for (let i = 0; i < goodsList.length; i++) {
            goodsList[i].stock = 0
          }
          this.isIndent = false
        } else {
          for (let i = 0; i < goodsList.length; i++) {
            var supplier_id = goodsList[i].supplier_id
            var goods_sku = goodsList[i].goods_sku
            if (res_freight['data'][supplier_id][goods_sku]['stockStateDesc'] == '有货') {
              goodsList[i].stock = 1
            } else {
              goodsList[i].stock = 0
              this.isIndent = false
            }
            if (supplier_id == -4) {
              goodsList[i].internal_price = res_freight['data'][supplier_id][goods_sku]['area_price']
            }

            // if (this.isIndent) {
            //   this.getJdFreight()
            // }
          }
        }
        this.$set(this.goodsList, goodsList, true)
        this.goodsList = goodsList
        for (let i = 0; i < goodsList.length; i++) {
          if (res_freight['data'][supplier_id][goods_sku]['stockStateDesc'] == '无货') {
            this.isIndent = false
            break
          }
        }

        this.isInventory = true
        this.$forceUpdate()

        // eslint-disable-next-line no-unreachable
        /*      let supplier_cart_list = this.supplier_cart_list
              if (supplier_cart_list[Enum.PRODUCT_SOURCE_TYPE.京东] && this.address) {
                let items = supplier_cart_list[Enum.PRODUCT_SOURCE_TYPE.京东]
                let param = {
                  skuStr: [],
                  code: this.address.alias,
                  area: this.address.area_info
                }
                items.map(item => {
                  param.skuStr.push({
                    skuId: item.other_sku,
                    num: item.goods_number
                  })
                })
                // eslint-disable-next-line no-unreachable
                param.skuStr = JSON.stringify(param.skuStr)
                this.$vux.loading.show({
                  text: '加载中'
                })
                let res = await Mall.getJdInventory(param)
                this.$vux.loading.hide()
                if (res.code == 0) {
                  let isIndent = true
                  for (var i in res.data) {
                    if (res.data[i].stockStateDesc != '有货') {
                      isIndent = false
                      break
                    }
                  }
                  if (isIndent) {
                    this.isIndent = true
                    //   this.getJdFreight()
                  }
                }
                // eslint-disable-next-line no-unreachable
              } else {
                this.isIndent = true
              } */
        this.getJdFreight()
      },
      // 获取JD运费
      async getJdFreight () {
        if (!this.goodsStockParams.area.area_code) {
          return
        }
        let params = {
          supplier_goods: JSON.stringify(this.goodsStockParams.supplier_goods),
          area_code: this.goodsStockParams.area.area_code
        }
        this.$vux.loading.show({
          text: '加载中'
        })
        let res_freight = await Mall.getJdFreight(params)
        this.$vux.loading.hide()
        if (res_freight.code != 0) {
          this.$vux.confirm.show({
            title: '提示',
            content: res_freight.msg,
            showCancelButton: false,
            onConfirm: () => {
              this.$router.back()
            }
          })
        }
        let freightList = res_freight.data
        let freight_total = 0
        for (let supplier_id in freightList) {
          freight_total += freightList[supplier_id].freight
          if (this.isJinDong(supplier_id) && freightList[supplier_id].freight) { // 判断是否有京东商品产生运费
            this.isJinDonFreight = true
          }
        }
        this.freight = freight_total * 1
        this.onTotal()
      },

      // 优惠券选中
      onHandleCoupon () {
        this.quotaId = 0
        this.finalQuotaAmount = 0
        this.quotaIndex = -1
        this.onTotal()
        this.onHideQuota()
      },

      // 合计
      onTotal () {
        let total = 0
        let reduce_amount = 0
        if (this.quotaId && this.isPayMethodQuota) { // 使用了额度并且是额度支付的情况下啊
          this.total = this.finalAmount
        } else {
          if (this.discountCouponListItem) {
            reduce_amount = this.discountCouponListItem.goods_reduce_amount
          }
          total = this.goods_total * 1 + this.freight - reduce_amount - this.finalQuotaAmounts
          this.total = total
        }
      },

      async getJsdkConfig () {
        // eslint-disable-next-line no-unused-vars
        let res = await Account.getJsdkConfig()
        // eslint-disable-next-line no-undef
        wx.ready(() => {
        })
      },

      // 额度弹框显示
      onShowQuota () {
        if (this.quotaList.length && !this.discountCouponListItem.id) {
          this.isQuota = true
        }
      },

      // 弹框隐藏
      onHideQuota () {
        this.isQuota = false
      },

      // 额度列表
      async getQuotaList () {
        let goodsItem = []
        let goodsItemNum = []
        this.goodsList.forEach((item) => {
          goodsItemNum.push(`${item.goods_sku}|${item.goods_number}`)
          goodsItem.push(item.goods_sku)
        })
        this.goodsItemNum = goodsItemNum
        this.goodsItem = goodsItem.join(',')
        let res = await Mall.getQuotaList({ goods_item: this.goodsItem })
        if (res.code == 0) {
          this.quotaList = res.data
          if ((this.isCQDX || this.isCQDXFK) && !this.quotaList.length) { // 重庆电信如果只有一张额度卡 默认选中
            if (this.quotaList.length) {
              this.payMethod = 0
            } else {
              this.payMethod = 1
            }
          }
          if (this.isPayMethodQuota && (this.isCQDX || this.isCQDXFK)) {
            if (this.quotaList.length === 1) { // 如果只有一张额度卡 默认选中
              this.onHandleQuota(this.quotaList[0], 0)
            }
            this.isQuota = (!this.isCQDX && !this.isCQDXFK) && !!this.quotaList.length
          }
        }
        // if (res.data && !res.data.length) {
        //   this.payMethod = 1
        // }
      },

      // 额度选择
      async onHandleQuota (item, index) {
        if (this.quotaIndex === index) {
          this.quotaIndex = -1
          this.quotaId = undefined
        } else {
          this.quotaIndex = index
          this.quotaId = item.id ? item.id : this.quotaId
        }
        let params = {
          goods_item: JSON.stringify(this.goodsItemNum) || undefined,
          coupon_id: this.quotaId ? undefined : this.discountCouponListItem.id,
          quota_id: this.discountCouponListItem.id ? 0 : this.quotaId,
          area_code: this.address.alias,
          supplier_goods: JSON.stringify(this.goodsStockParams.supplier_goods)
        }
        this.$vux.loading.show({
          text: '请稍后'
        })
        let res = await Mall.getQuotaListDetail(params)
        this.$vux.loading.hide()
        if (res.code == 0) {
          let { data } = res
          this.finalQuotaAmount = data.final_quota_amount || 0
          this.finalAmount = data.final_amount || 0
          this.quotaGoods = data.quota_goods
          this.isQuotaPass = parseFloat(data.quota_pass)
          this.phone = data.phone
          this.onTotal()
        } else {
          this.$vux.toast.text(res.msg)
        }
      },

      // 设置密码成功后 改变状态
      setQuotaPass () {
        this.isQuotaPass = 1
      },

      // 支付方式弹框
      onShowMethod () {
        this.isPayMethod = true
      },

      // 支付方式选择
      onMethodList (val) {
        if (val == 0 || val == 1) {
          this.payMethod = val
        }
      },

      // 发票信息是否完善
      invoicePerfect (param) {
        this.isInvoicePerfect = param
      },

      // 删除无货商品
      deleteNoStockGoods (item) {
        let buyItem = this.items
        let _buyItem = []
        let idOrSku = parseFloat(item.cart_id) ? item.cart_id : item.goods_sku
        let idOrSkuKey = parseFloat(item.cart_id) ? 'cart_id' : 'goods_sku'
        _buyItem = buyItem.filter((child) => parseFloat(child[idOrSkuKey]) !== parseFloat(idOrSku))
        this.$vux.confirm.show({
          title: '提示',
          content: '此操作将删除所选商品, 是否继续?',
          showCancelButton: true,
          onConfirm: () => {
            if (_buyItem.length) {
              this.items = _buyItem
              this.$router.replace({ query: { items: JSON.stringify(_buyItem), if_cart: this.if_cart } })
            } else {
              this.$router.go(-1)
            }
          }
        })
      },

      // 只有一张额度卡默认选中
      defaultCheckedAmount () {
        if (this.quotaList.length === 1) { // 如果只有一张额度卡 默认选中
          this.onHandleQuota(this.quotaList[0], 0)
        }
      },
      // 返回首页
      goBack () {
        this.globalData.tempAddressSelect = null
        this.$router.go(-1)
      }
    }
  }
</script>

<style lang="less" scoped>
  .wxPayUrl {
    margin: 0;
    padding: 0;
    height: 100%;
    width: 100%;
    border: none;
  }

  ul {
    margin: 0;
    padding: 0;
    list-style: none;
  }

  .addressitembox {
    display: flex;
    align-items: center;
    padding: 24px;
    background-color: #fff;
  }

  .addressitembox .header {
    display: flex;
    justify-content: space-between;
    font-size: 16px;
    color: #351009;
    line-height: 22px;
  }

  .addressitembox .address {
    font-size: 12px;
    color: #351009;
    line-height: 17px;
    margin-top: 12px;
  }

  .addressitembox .query {
    font-size: 14px;
    color: #351009;
    line-height: 20px;
    margin-top: 24px;
    display: block;
  }

  .item {
    display: flex;
    flex-direction: row;
    padding: 12px 16px;
    background-color: #fff;
  }

  .item .image {
    width: 100px;
    height: 100px;
    display: block;
    background-color: #f5f5f5;
  }

  .item .content {
    flex: 1;
    margin-left: 16px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }

  .item .content .title, .shopQuotaSidebar-content-list-text-desc {
    font-size: 12px;
    color: #9f8d89;
    line-height: 17px;
    /*height: 34px;*/
    font-weight: 500;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
    text-overflow: ellipsis;
    overflow: hidden;
  }

  .item .content .title {
    -webkit-line-clamp: 2;
    height: 34px;
  }

  .item .content .price {
    font-size: 14px;
    color: #351009;
    line-height: 16px;
    flex-shrink: 0;
    margin-left: 10px;
  }

  .item .content .num {
    margin-top: 4px;
    font-size: 14px;
    color: #351009;
    line-height: 16px;
  }

  .block + .blockgrod,
  .blockgrod + .blockgrod,
  .blockgrod + .block {
    margin-top: 15px;
  }

  .blockgrod > .block + .block {
    margin-top: 0;
  }

  .listitem {
    display: flex;
    flex-direction: row;
    padding: 10px 20px 10px 16px;
    background-color: #fff;
    align-items: center;
  }

  .listitem .icon {
    width: 28px;
    height: 28px;
    display: block;
    margin-right: 8px;
  }

  .listitem .text {
    flex: 1;
    font-size: 12px;
    color: #666666;
    line-height: 21px;
  }

  .listitem .right {
    font-size: 12px;
    margin-left: 8px;
    color: #666666;
    display: block;
  }

  .listitem .righticon {
    margin-left: 8px;
    height: 20px;
    width: 20px;
    display: block;
  }

  .quotatPay .right {
    color: #b0290f;
    cursor: pointer;
  }

  /*额度列表*/
  .shopQuotaSidebar {
    padding: 10px 28px;
    font-size: 12px;
    overflow-y: scroll;
    position: fixed;
    right: 0;
    left: 0;
    bottom: 0;
    top: 0;
    z-index: 100;
    background: #fff;

    .shopQuotaSidebar-tit {
      text-align: center;
    }

    .shopQuotaSidebar-tit-de {
      padding: 13px;
      width: 30%;
      margin: 0 auto;
      border-bottom: 2px solid #b0290f;
      color: #b0290f;
      margin-bottom: 13px;
    }

    .shopQuotaSidebar-content {
      padding: 0;
      list-style: none;
      height: 74%;
      overflow: auto;

      .shopQuotaSidebar-content-box {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
      }

      .shopQuotaSidebar-content-list {
        box-sizing: border-box;
        color: #fff;
        width: 100%;
        height: auto;
        max-height: 132px;
        padding: 10px;
        margin-bottom: 10px;
        border-radius: 11px;
        background-image: url("../../../assets/img/icon_quota.png");
        background-size: cover;
        position: relative;
        overflow: hidden;

        .shopQuotaSidebar-content-list-text-desc {
          color: #fff;
          height: auto;
          line-height: 25px;
        }

        .shopQuotaSidebar-content-list-text-price {
          font-size: 15px;
          font-weight: bold;
        }

        .quotaItem-content-list-name {
          font-size: 15px;
          width: 90%;
          display: -webkit-box !important;
          -webkit-line-clamp: 1;
          -webkit-box-orient: vertical;
          text-overflow: ellipsis;
          overflow: hidden;
        }

        .quotaItem-content-list-min {
          position: absolute;
          right: 3%;
          top: 7%;
          width: 22px;
          height: 22px;
        }

        .shopQuotaSidebar-content-list-text {
          display: flex;
          margin: 3px 0;
          line-height: 25px;

          .shopQuotaSidebar-content-list-text-tit {
            margin-right: 10px;
            /*width: 55px;*/
            text-align: right;
            flex-shrink: 0;
          }
        }
      }

      div.shopQuotaSidebar-content-list-checked {
        background-image: url("../../../assets/img/icon_quota_checked.png");
      }
    }

    /*额度适用商品*/

    .quota-goods {
      margin: 15px 0;
      border-top: 1px solid #999;
      font-size: 12px;
      width: 90%;

      .quota-goods-desc {
        padding: 8px;

        .app-new-price-bold {
          font-size: 14px;
          color: #b0290f;
          font-weight: bold;
        }
      }

      .quota-goods-con {
        display: flex;
        flex-wrap: wrap;

        .quota-goods-con-list {
          overflow: hidden;
          width: 30%;
          border: 1px solid #ccc;
          padding-top: 5px;
          display: flex;
          align-items: center;
          flex-direction: column;
          margin: 1%;

          .quota-goods-con-list-img {
            max-width: 60px;
            max-height: 60px;
          }

          .quota-goods-con-list-price {
            margin-top: 5px;
            border-top: 1px solid #ccc;
            padding: 3px;
            width: 100%;
            text-align: center;

            .link-active-class {
              margin-left: 3px;
              color: #b0290f;
            }
          }
        }
      }
    }
  }

  /*无货提示*/
  .noGoods {
    /*background: rgba(241, 241, 241, 0.56) !important;*/
    position: relative;

    .price, .num, .title {
      color: #a99b98 !important;
      text-decoration: line-through;
    }
  }

  .noGoods-text {
    /*position: absolute;*/
    /*bottom: 7px;*/
    /*right: 7px;*/
    font-size: 12px;
    color: #fe0000;
    text-align: left;
    display: flex;
    justify-content: space-between;

    .noGoods-text-btn {
      padding: 1px 3px;
      border: 1px solid #fe0000;
    }
  }

  .noGoods-tip {
    color: #b0290f;
    position: absolute;
    font-size: 12px;
    top: -20px;
  }

  .button-noGoods {
    background: #b6b6b6 !important;
  }
</style>
